#    This is part of WeatherFront.
#
#    Copyright (C) 2010 Stefan Sieber
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; version 2 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


import objc
import Foundation
import AppKit
import time

import PyFR.Utilities

import urllib2
import re
import string

from WeatherFrontXMLScanner import *



verbose=1
def log(s,level=1):
	if verbose >= level:
		Foundation.NSLog( u"%s: WeatherAPI: %@", "WeatherFrontLog", s ) 
	pass

class WeatherDotComCompiler:
	def __init__(self, xml_stream):
		self = self
		self.xml_stream = xml_stream

	""" Returns the content of a given tag in a stream as SEQUENCE like mySubSet=[]
		The value of the sequence will be an amount of DICTIONARYs like myDict={'DATA': 'Dortmund'} 
		
		Sample
		tmp = self.getSubSet(currentConditions[0], 't') // tag = 't' like for text
		occurence: 4 
		print tmp	 >> [[{'DATA': 'Partly'}, {'DATA': 'Cloudy'}], [{'DATA': 'W'}], [{'DATA': 'Low'}], [{'DATA': 'First'}, {'DATA': 'Quarter'}]] 
		print tmp[2] >> [{'DATA': 'Low'}]
	"""
	def getSubSet(self, stream, tag):
		occurCounter=0
		i=0
		startPos=[]
		endPos=[]
		#print i, startPos, endPos, tag
		#print "***\n", stream, "***\n"
		for item in stream:
			i+=1
			if item.has_key(tag):
				if item.get(tag) == 'START':
					occurCounter += 1
					startPos.append(i)
				if item.get(tag) == 'END':
					endPos.append(i-1)
		#print occurCounter, startPos, endPos
		i=0
		returnValue=[]
		while i < occurCounter:
			returnValue.append(stream.__getslice__(startPos[i],endPos[i]))
			i+=1;
		return returnValue
	
	"""
		getCurrentConditions 
	"""
	def getCurrentConditions(self, weatherItem):
		value = []
		i = 0
		
		units = ""
		units = self.getSubSet(self.xml_stream, 'head')
		currentLocation = ""
		currentLocation = self.getSubSet(self.xml_stream, 'loc')
		currentConditions = ""
		currentConditions = self.getSubSet(self.xml_stream, 'cc')
		#print occur, currentConditions
		
	
		weatherItem.caption = "Current"
		
		for item in (self.getSubSet(units[0], 'us'))[0]: # km/h mp/h
			#log(item.get('DATA'))
			weatherItem.unitSpeed = item.get('DATA')
		for item in (self.getSubSet(units[0], 'ut'))[0]: # F/C
			#log(item.get('DATA'))
			weatherItem.unitTemp = item.get('DATA')
		
		for item in (self.getSubSet(currentLocation[0], 'dnam'))[0]: #Selected City + Country
			#log(item.get('DATA'))
			value.append(item.get('DATA'))
		weatherItem.location = string.join(value, " ")
		value = []
			
		for item in (self.getSubSet(currentConditions[0], 'lsup'))[0]: #Last Update
			if i > 2:
				break
			value.append(item.get('DATA'))
			i+=1
		weatherItem.date = string.join(value, " ")
		value = []; i=0
		
		for item in (self.getSubSet(currentConditions[0], 'obst'))[0]: # location
			#log(item.get('DATA'))
			pass
		for item in (self.getSubSet(currentConditions[0], 'tmp'))[0]: # tmperature
			#log(item.get('DATA'))
			weatherItem.temp1 = item.get('DATA')
		for item in (self.getSubSet(currentConditions[0], 'flik'))[0]: # feels like
			#log(item.get('DATA'))
			weatherItem.temp2 = item.get('DATA')
		for item in (self.getSubSet(currentConditions[0], 't'))[0]: # text 1
			#log(item.get('DATA'))
			weatherItem.text = item.get('DATA')
		for item in (self.getSubSet(currentConditions[0], 'icon'))[0]: # icon 1
			#log(item.get('DATA'))
			weatherItem.icon = item.get('DATA')
		for item in (self.getSubSet(self.getSubSet(currentConditions[0], 'wind')[0], 's'))[0]: # wind - strength
			#log(item.get('DATA'))
			weatherItem.windStrength = item.get('DATA')
		for item in (self.getSubSet(self.getSubSet(currentConditions[0], 'wind')[0], 'd'))[0]: # wind
			#log(item.get('DATA'))
			pass
		for item in (self.getSubSet(self.getSubSet(currentConditions[0], 'wind')[0], 't'))[0]: # wind
			#log(item.get('DATA'))
			weatherItem.windFrom = item.get('DATA')
		for item in (self.getSubSet(currentConditions[0], 'hmid'))[0]: # humidity
			#log(item.get('DATA'))
			weatherItem.hmid = item.get('DATA')
		for item in (self.getSubSet(self.getSubSet(currentConditions[0], 'moon')[0], 'icon'))[0]: # moon
			#log(item.get('DATA'))
			pass
		for item in (self.getSubSet(self.getSubSet(currentConditions[0], 'moon')[0], 't'))[0]: # moon
			#log(item.get('DATA'))
			pass	
			
			
			
	"""
		getForecast 
	"""
	def getForecast(self, weatherItem):
		log("WeatherDotComCompiler::getForecast - item: %s" % weatherItem.id)
		forDay=weatherItem.id
		value = []
		i = 0
		
		
		units = ""
		units = self.getSubSet(self.xml_stream, 'head')
		forecast = ""
		forecast = self.getSubSet(self.xml_stream, 'dayf')
		day = ""
		day = (self.getSubSet(forecast[0], 'day'))[forDay]
		
		
		for item in (self.getSubSet(units[0], 'us'))[0]: # km/h mp/h
			#log(item.get('DATA'))
			weatherItem.unitSpeed = item.get('DATA')
		for item in (self.getSubSet(units[0], 'ut'))[0]: # F/C
			#log(item.get('DATA'))
			weatherItem.unitTemp = item.get('DATA')
			
	
		for item in day:
			if i > 0:
				break
			value = item.get('DATA')
			i+=1
		weatherItem.caption = value.get('t')
		weatherItem.date = value.get('dt')
		value = []; i=0
		
		
		for item in (self.getSubSet(day, 'hi'))[0]: # high-tmp
			#log(item.get('DATA'))
			weatherItem.temp1 = item.get('DATA')
		for item in (self.getSubSet(day, 'low'))[0]: # low-tmp
			#log(item.get('DATA'))
			weatherItem.temp2 = item.get('DATA')
		for item in (self.getSubSet(self.getSubSet(day, 'part')[0], 't'))[0]: # desc
			#log(item.get('DATA'))
			weatherItem.text = item.get('DATA')
		for item in (self.getSubSet(self.getSubSet(day, 'part')[0], 'icon'))[0]: # icon
			#log(item.get('DATA'))
			weatherItem.icon = item.get('DATA')
	
			
					
					

	"""
		getLocationID 
	"""
	def getLocationID(self, city, country):
		log("WeatherDotComCompiler::getLocationID")
		compareToCity = city
		compareToCountry = country
		foundLocation = 0
		locID = ''
		tmpLocID = ''
		i = 0

		
		location = ""
		location = self.getSubSet(self.xml_stream, 'search')
		#log(locations)
		cities = ""
		cities = self.getSubSet(location[0], 'loc')
		#log(cities)
		
		log("Found %s cities" % cities.__len__())
		
		if cities.__len__() > 0:
			for city in cities:
				#log(city)
				i=0
				for item in city:
					if i == 0:
						value = item.get('DATA')
						tmpLocID = value.get('id')
					if i == 2:
						if item.get('DATA') == compareToCountry: # found location in right country?!
							log('Match country')
							foundLocation = 1
							locID = tmpLocID
							break
					i+=1
			
			if not foundLocation:
				log('No match for city & country, just select the first in the list')
				city = self.getSubSet(location[0], 'loc')[0] # just choose the first in the list
				for item in city:
					if i == 0:
						value = item.get('DATA')
						locID = value.get('id')
						i+=1
		else:
			log('No location found, choose default')
			locID = 'USCA0273' 
		log('Selected Location ID: %s' % locID)
		return locID
		


